//
//  SFTextImageButton.m
//  SinaFinance
//
//  Created by zhoucheng on 2018/5/23.
//  Copyright © 2018年 sina.com. All rights reserved.
//

#import "SFTextImageButton.h"

@interface SFTextImageButton()

@end

@implementation SFTextImageButton

- (void)setConfig:(SFTextImageButtonConfig)config
{
    if (_config != config) {
        _config = config;
        [self reloadButtonImageText];
    }
}

- (void)setSpace:(CGFloat)space
{
    if (_space != space) {
        _space = space;
        [self reloadButtonImageText];
    }
}

- (void)reloadButtonImageText
{
    if (!self.imageView.image) {
        [self setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)];
        [self setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)];
        return;
    }
    
    CGFloat spacing = self.space / 2;
    
    if (self.config == SFTextImageButtonConfig_ImageRight_TextLeft) {

        CGFloat btnImageWidth = self.imageView.bounds.size.width;
        CGFloat btnLabelWidth = self.titleLabel.bounds.size.width;
        
        btnImageWidth += spacing;
        btnLabelWidth += spacing;
        
        [self setTitleEdgeInsets:UIEdgeInsetsMake(0.0, -btnImageWidth, 0.0, btnImageWidth)];
        [self setImageEdgeInsets:UIEdgeInsetsMake(0.0, btnLabelWidth, 0.0, -btnLabelWidth)];
        
        if (self.imageView.x < (self.titleLabel.width + self.titleLabel.x)) {
            self.imageView.x = (self.titleLabel.width + self.titleLabel.x + spacing);
        }
        
    }else if (self.config == SFTextImageButtonConfig_Normal)
    {
        [self setTitleEdgeInsets:UIEdgeInsetsMake(0.0, spacing, 0.0, 0.0)];
        [self setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0, spacing)];
    }
}

- (void)setTitle:(NSString *)title forState:(UIControlState)state
{
    [super setTitle:title forState:state];
    if (self.space || self.config) {
        [self reloadButtonImageText];
    }
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state
{
    [super setImage:image forState:state];
    if (self.space || self.config) {
        [self reloadButtonImageText];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self reloadButtonImageText];
}

@end
